package gamagora.game.entity
{
	import gamagora.game.world.maps.OSMap;
	
	import org.flixel.FlxObject;
	import org.flixel.FlxSound;
	
	public class OSSound extends OSEntity
	{
		private var _sound:FlxSound;
		
		public function OSSound(X:Number, Y:Number, volume:Number = 0.5, SimpleGraphic:Class=null)
		{
			super(NOTHING, X, Y, SimpleGraphic);
			_hide = true;
			
			_sound = new FlxSound();
			_sound.x = X;
			_sound.y = Y;
			_sound.volume = volume;
		}
		
		public function loadEmbedded(EmbeddedSound:Class, Looped:Boolean=false, AutoDestroy:Boolean=false):FlxSound
		{
			return _sound.loadEmbedded(EmbeddedSound, Looped);
		}
		
		private function findVolumeFromPlayer():Number
		{
			var dist:Number =  Math.abs(x - _world.getPlayerX());
			if(dist < OSMap.WIDTH)
			{
				return 1 - (dist / OSMap.WIDTH);
			}
			else
			{
				return 0;
			}
		}
		
		//Override
		
		public override function addToWorld():void
		{
			_inWorld = true;
			_world.add(_sound);
			_sound.play();
		}
		
		public override function removeFromWorld():void
		{
			_inWorld = false;
			_world.remove(_sound, true);
			_sound.stop();
		}
		
		public override function update():void
		{
			_sound.volume = findVolumeFromPlayer();
		}

		public override function setStartX(decalX:Number):void
		{
			super.setStartX(decalX);
			_sound.x = x;
		}
		
		public override function destroy():void
		{
			super.destroy();
			_sound.destroy();
		}
	}
}